//
//  GMInputViewPluginView.m
//  Gmall
//
//  Created by yemeihua on 15/11/25.
//  Copyright © 2015年 Gmall. All rights reserved.
//

#import "GMInputViewPluginView.h"

@implementation GMInputViewPluginView

- (instancetype)initWithFrame:(CGRect)frame titleItems:(NSArray<NSDictionary *> *)titleItems imageItems:(NSArray<NSDictionary *> *)imageItems
{
    if(self = [super initWithFrame:frame])
    {
        self.buttons = [[NSMutableArray alloc] init];
        self.items = [[NSMutableArray alloc] init];
        
        [self.items addObjectsFromArray:titleItems];
        [self.items addObjectsFromArray:imageItems];
        
        self.backgroundColor = [UIColor yc_colorWithUInt:0xf6f6f7];
        
        CGFloat width = (kScreenWidth - 120) / titleItems.count;
        CGRect rect = CGRectMake(60, 60, width, 44.0);
        
        for(NSDictionary *item  in titleItems)
        {
            UIButton *button = [[UIButton alloc] initWithFrame:rect];
            [button setTitle:item[@"t"] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor yc_colorWithUInt:0x00b4ff] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(didTouchUpInsideItemButton:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
            rect = CGRectOffset(rect, CGRectGetWidth(rect), 0);
            [self.buttons addObject:button];
        }
        
        CGFloat margin = (kScreenWidth - imageItems.count * 44) / (imageItems.count + 1);
        rect = CGRectMake(margin, 124, 44.0, 70.0);
        
        for(NSDictionary *item in imageItems)
        {
            UIButton *button = [[UIButton alloc] initWithFrame:rect];
            [button setTitle:item[@"t"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:item[@"i"]] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:12];
            [button setTitleEdgeInsets:UIEdgeInsetsMake(40, -43, 0, 0)];
            [button setImageEdgeInsets:UIEdgeInsetsMake(-10, 0, 20, 0)];
            [button addTarget:self action:@selector(didTouchUpInsideItemButton:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
            rect = CGRectOffset(rect, CGRectGetWidth(rect) + margin, 0);
            [self.buttons addObject:button];
        }
    }
    return self;
}

- (void)didTouchUpInsideItemButton:(UIButton *)button
{
    if([self.delegate respondsToSelector:@selector(pluginView:didTouchUpInsideItem:)])
    {
        NSInteger index = [self.buttons indexOfObject:button];
        NSDictionary *item = [self.items objectAtIndex:index];
        [self.delegate pluginView:self didTouchUpInsideItem:item];
    }
}

@end
